package com.framework.service.core.service.impl;


import com.alibaba.fastjson.JSON;
import com.framework.service.core.biz.ICustomInfoBiz;
import com.framework.service.core.dao.mapper.CityMapper;
import com.framework.service.core.dao.mapper.CustomInfoMapper;
import com.framework.service.core.dao.mapper.GuideInfoMapper;
import com.framework.service.core.dao.mapper.ThirdUserInfoMapper;
import com.framework.service.core.dao.mapper.old.UserDataMapper;
import com.framework.service.core.dao.mapper.old.UserMapper;
import com.framework.service.core.dao.mapper.old.UserRoleMapper;
import com.framework.service.core.dao.model.City;
import com.framework.service.core.dao.model.CustomInfo;
import com.framework.service.core.dao.model.GuideInfo;
import com.framework.service.core.dao.model.ThirdUserInfo;
import com.framework.service.core.dao.model.old.User;
import com.framework.service.core.dao.model.old.UserData;
import com.framework.service.core.dao.model.old.UserRole;
import com.framework.service.core.service.ICityService;
import com.framework.service.core.service.ICustomInfoService;
import com.framework.auth.api.feign.RemoteAuthService;
import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.Enums.UserTypeEnum;
import com.framework.common.Enums.UserVerifyStatusEnum;
import com.framework.common.exception.BusinessException;
import com.framework.common.request.CustomInfoReq;
import com.framework.common.util.IDCardUtil;
import com.framework.common.util.ValidateUtil;
import com.framework.core.api.request.CustomInfoCertReq;
import com.framework.core.api.request.CustomInfoQuerytReq;
import com.framework.core.api.response.CustomInfoRes;
import com.framework.service.core.biz.ICustomInfoBiz;
import com.framework.service.core.dao.mapper.CityMapper;
import com.framework.service.core.dao.mapper.CustomInfoMapper;
import com.framework.service.core.dao.mapper.GuideInfoMapper;
import com.framework.service.core.dao.mapper.ThirdUserInfoMapper;
import com.framework.service.core.dao.mapper.old.UserDataMapper;
import com.framework.service.core.dao.mapper.old.UserMapper;
import com.framework.service.core.dao.mapper.old.UserRoleMapper;
import com.framework.service.core.dao.model.City;
import com.framework.service.core.dao.model.CustomInfo;
import com.framework.service.core.dao.model.GuideInfo;
import com.framework.service.core.dao.model.ThirdUserInfo;
import com.framework.service.core.dao.model.old.User;
import com.framework.service.core.dao.model.old.UserData;
import com.framework.service.core.dao.model.old.UserRole;
import com.framework.service.core.service.ICityService;
import com.framework.service.core.service.ICustomInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 客户管理服务
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/11 16:23
 * @since JDK 1.8
 */
@Service
@Slf4j
public class CustomInfoServiceImpl implements ICustomInfoService {

    @Autowired
    private ICustomInfoBiz customInfoBiz;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserDataMapper userDataMapper;

    @Autowired
    private CustomInfoMapper customInfoMapper;

    @Autowired
    private ThirdUserInfoMapper thirdUserInfoMapper;

    @Autowired
    private ICityService cityService;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private GuideInfoMapper guideInfoMapper;

    @Autowired
    private RemoteAuthService remoteAuthService;

    // 用户认证必填字段
    private static final String[] CERT_REQUIRED_FIELDS;

    static {
        CERT_REQUIRED_FIELDS = new String[] {
                "userId", "phoneNum", "realName", "cardType", "cardNo", "userType", "idCardFrontPath",
                "idCardBackPath", "idCardHoldPath", "certValidDate"
        };
    }

    @Override
    public int insertCustomInfo(CustomInfo customInfo) {
       // return customInfoMapper.insertCustomSelective(customInfo);
        return 0;
    }

    @Override
    public CustomInfoRes certCustomInfo(CustomInfoCertReq customInfoCertReq) {
        CustomInfoRes customInfoRes = new CustomInfoRes();
        if (null == customInfoCertReq) {
            log.warn("[用户实名认证]-请求参数为空");
            customInfoRes.setCode(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getMsg());
            return customInfoRes;
        }
        log.info("correctionId=[{}]-[用户实名认证]-开始-请求参数=[{}]", customInfoCertReq.getCorrelationID(), JSON.toJSONString(customInfoCertReq));
        // 必填参数校验
        try {
            ValidateUtil.requiredFieldsChk(customInfoCertReq, CERT_REQUIRED_FIELDS);
            customInfoCertReq.setGender(IDCardUtil.getSex(customInfoCertReq.getCardNo()));
            // 这里的userId暂时是老数据库的user，需要先转换成openId
            User user = userMapper.selectById(customInfoCertReq.getUserId().intValue());
            if(user == null) {
                customInfoRes.setCode(FrameworkErrorCodeEnum.USER_NOT_EXITS.getCode());
                customInfoRes.setMsg(FrameworkErrorCodeEnum.USER_NOT_EXITS.getMsg());
                return customInfoRes;
            }
            // 用openId查询第三方用户
            ThirdUserInfo thirdUserInfo = thirdUserInfoMapper.getThirdUserInfoByOpenId(user.getOpenId());
            customInfoCertReq.setOpenId(thirdUserInfo.getOpenId());
            if(thirdUserInfo.getUserId() == null) {
                // 新增认证信息
                customInfoBiz.certCustomNew(customInfoCertReq);
            } else {
                // 更新认证信息
                customInfoCertReq.setUserId(thirdUserInfo.getUserId());
                customInfoBiz.certCustomUpdate(customInfoCertReq);
            }
            BeanUtils.copyProperties(customInfoCertReq, customInfoRes);
            if(StringUtils.equals(UserTypeEnum.GUIDE.getValue().toString(), customInfoCertReq.getUserType())) {
                customInfoRes.setUserVerifyStatus(UserVerifyStatusEnum.APPROVED.getCode());
            }

            customInfoRes.setRoleId(Integer.valueOf(customInfoCertReq.getUserType()));
            customInfoRes.setCode(FrameworkErrorCodeEnum.SUCCESS.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.SUCCESS.getMsg());
            log.info("correlationID=[{}]-[用户实名认证]-结束-[{}]", customInfoCertReq.getCorrelationID(), JSON.toJSONString(customInfoRes));
        } catch (BusinessException e) {
            log.error("correlationID=[{}]-[用户实名认证]-业务异常-code=[{}]-msg=[{}]", customInfoCertReq.getCorrelationID(), e.getErrorCode(), e.getErrorMessage(),
                    e);
            customInfoRes.setCode(e.getErrorCode());
            customInfoRes.setMsg(e.getErrorMessage());
            return customInfoRes;
        } catch (Exception e) {
            if(e instanceof DuplicateKeyException) {
                log.error("correlationID=[{}]-[用户实名认证]-该用户已完成实名认证", customInfoCertReq.getCorrelationID(), e);
                customInfoRes.setCode(FrameworkErrorCodeEnum.USER_HAS_ALREADY_CERT.getCode());
                customInfoRes.setMsg(FrameworkErrorCodeEnum.USER_HAS_ALREADY_CERT.getMsg());
                return customInfoRes;
            }
            log.error("correlationID=[{}]-[用户实名认证]-系统异常", customInfoCertReq.getCorrelationID(), e);
            customInfoRes.setCode(FrameworkErrorCodeEnum.SYSTEM_ERR.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.SYSTEM_ERR.getMsg());
            return customInfoRes;
        }

        try{
            UserRole userRole = new UserRole(customInfoCertReq.getUserId().intValue(), customInfoRes.getRoleId(), LocalDateTime.now());
            UserData userData = new UserData(customInfoCertReq.getUserId().intValue(), 0, 0, 0, 0, 0, 0, 0, 0, 100, null);
            userRoleMapper.insert(userRole);
            userDataMapper.insert(userData);
        } catch (Exception e) {
           log.warn("correlationID=[{}]-[用户实名认证]-老版团团用户已拥有该角色", customInfoCertReq.getCorrelationID());
        }

        CustomInfoReq customInfoReq = new CustomInfoReq();
        BeanUtils.copyProperties(customInfoCertReq, customInfoReq);
        customInfoReq.setUserId(customInfoCertReq.getUserId().intValue());
        remoteAuthService.refreshTtzAuthentication(customInfoReq);
        return customInfoRes;
    }

    @Override
    public CustomInfoRes getCustomInfo(CustomInfoQuerytReq customInfoQuerytReq) {
        CustomInfoRes customInfoRes = new CustomInfoRes();
        if (null == customInfoQuerytReq) {
            log.warn("[获取用户信息]-请求参数为空");
            customInfoRes.setCode(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getMsg());
            return customInfoRes;
        }
        log.info("correctionId=[{}]-[用户信息查询]-开始-请求参数=[{}]", customInfoQuerytReq.getCorrelationID(), JSON.toJSONString(customInfoQuerytReq));

        try{
            // 查询customer表
            CustomInfo customInfo = customInfoMapper.selectByPrimaryKey(customInfoQuerytReq.getUserId());
            if(customInfo == null) {
                log.warn("correctionId=[{}]-[用户信息查询]-该用户不存在-用户id=[{}]", customInfoQuerytReq.getCorrelationID(), customInfoQuerytReq.getUserId());
                customInfoRes.setCode(FrameworkErrorCodeEnum.USER_NOT_EXITS.getCode());
                customInfoRes.setMsg(FrameworkErrorCodeEnum.USER_NOT_EXITS.getMsg());
                return customInfoRes;
            }
            BeanUtils.copyProperties(customInfo, customInfoRes);
            // 城市id转换
            if(StringUtils.isNotBlank(customInfoRes.getCityId())) {
                City city = cityMapper.selectById(customInfoRes.getCityId());
                if(city != null) {
                    customInfoRes.setCityName(city.getShortName());
                }
            }
            customInfoRes.setRoleId(Integer.valueOf(customInfoRes.getUserType()));
            //
            if(StringUtils.equals(UserTypeEnum.GUIDE.getValue().toString(), customInfo.getUserType())) {
                GuideInfo guideInfo = guideInfoMapper.selectByPrimaryKey(customInfoQuerytReq.getUserId());
                if(guideInfo != null) {
                    customInfoRes.setUserVerifyStatus(guideInfo.getStatus());
                    customInfoRes.setGuideTourId(guideInfo.getGuideTourId());
                }
            }
//            // 查询老的user表，获取userId和roleId
//            User user = userMapper.selectById(customInfoQuerytReq.getUserId().intValue());
//            if(user != null) {
//                List<Integer> roleIds = userRoleMapper.queryUserRoles(user.getId());
//                if (roleIds != null && !roleIds.isEmpty()) {
//                    customInfoRes.setRoleId(roleIds.get(0));
//                }
//                customInfoRes.setUserId(user.getId().longValue());
//                customInfoRes.setAvatarUrl(user.getAvatarUrl());
//                customInfoRes.setGender(user.getGender().toString());
//                customInfoRes.setNickName(user.getNickname());
//
//                ThirdUserInfo thirdUserInfo = thirdUserInfoMapper.getThirdUserInfoByOpenId(user.getOpenId());
//                customInfoRes.setCityId(thirdUserInfo.getCityId());
//                // 城市id转换
//                if(StringUtils.isNotBlank(customInfoRes.getCityId())) {
//                    City city = cityMapper.selectById(customInfoRes.getCityId());
//                    if(city != null) {
//                        customInfoRes.setCityName(city.getShortName());
//                    }
//                }
//            }
            UserData userData = userDataMapper.selectByUserId(customInfoQuerytReq.getUserId().intValue());
            if(userData != null) {
                Integer userScore = 0;
                Integer touristScore = 0;
                if (userData.getUserNumber() != 0) {
                    userScore = userData.getUserScore() / userData.getUserNumber();
                }
                if (userData.getTouristNumber() != 0) {
                    touristScore = userData.getTouristScore() / userData.getTouristNumber();
                }
                customInfoRes.setUserScore(userScore);
                customInfoRes.setTouristScore(touristScore);
                customInfoRes.setTotalFee(userData.getTotalFee());
                customInfoRes.setVisitorNumber(userData.getVisitorNumber());
                customInfoRes.setItemNumber(userData.getItemNumber());
                customInfoRes.setCredit(userData.getCredit());
            }




            customInfoRes.setCode(FrameworkErrorCodeEnum.SUCCESS.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.SUCCESS.getMsg());
            log.info("correctionId=[{}]-[用户信息查询]-结束-查询结果=[{}]", customInfoQuerytReq.getCorrelationID(), JSON.toJSONString(customInfoRes));
            return customInfoRes;
        }catch (Exception e) {
            log.error("correlationID=[{}]-[用户信息查询]-系统异常", customInfoQuerytReq.getCorrelationID(), e);
            customInfoRes.setCode(FrameworkErrorCodeEnum.SYSTEM_ERR.getCode());
            customInfoRes.setMsg(FrameworkErrorCodeEnum.SYSTEM_ERR.getMsg());
            return customInfoRes;
        }
    }
}
